package services

import (
    "sync"
    "time"
)

type DiscoveryService struct {
    mu         sync.RWMutex
    subsystems map[string]*SubsystemInfo
    paths      map[string][]PathInfo // 修正类型定义
}

type SubsystemInfo struct {
    NQN          string     `json:"nqn"`
    Addresses    []string   `json:"addresses"`
    SerialNumber string     `json:"serial_number"`
    Model        string     `json:"model"`
    Paths        []PathInfo `json:"paths"`
}

type PathInfo struct {
    Address    string  `json:"address"`
    Port       int     `json:"port"`
    Transport  string  `json:"transport"`
    Status     string  `json:"status"`
    RTT        float64 `json:"rtt"`
    Priority   int     `json:"priority"`
}

func NewDiscoveryService() *DiscoveryService {
    ds := &DiscoveryService{
        subsystems: make(map[string]*SubsystemInfo),
        paths:      make(map[string][]PathInfo),
    }
    go ds.monitor()
    return ds
}

func (ds *DiscoveryService) monitor() {
    ticker := time.NewTicker(10 * time.Second)
    for range ticker.C {
        ds.updatePathStatus()
    }
}

func (ds *DiscoveryService) updatePathStatus() {
    ds.mu.Lock()
    defer ds.mu.Unlock()

    for nqn, pathList := range ds.paths {
        for i := range pathList {
            // 测试路径延迟和状态
            rtt, err := ds.testPath(pathList[i])
            if err != nil {
                pathList[i].Status = "down"
            } else {
                pathList[i].Status = "up"
                pathList[i].RTT = rtt
            }
        }
        // 更新修改后的切片
        ds.paths[nqn] = pathList
        // 根据RTT更新路径优先级
        ds.updatePathPriorities(nqn)
    }
}

func (ds *DiscoveryService) testPath(path PathInfo) (float64, error) {
    // 实现路径测试逻辑，返回RTT
    return 0.0, nil
}

func (ds *DiscoveryService) updatePathPriorities(nqn string) {
    pathList := ds.paths[nqn]
    // TODO: 实现路径优先级排序
    for i := range pathList {
        pathList[i].Priority = i
    }
    ds.paths[nqn] = pathList
}

func (ds *DiscoveryService) GetPathsForSubsystem(nqn string) []PathInfo {
    ds.mu.RLock()
    defer ds.mu.RUnlock()
    return ds.paths[nqn]
}
